//
//  MQVideoEntertainmentViewController.m
//  MQ
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 徐永祥. All rights reserved.
//

#import "MQVideoEntertainmentViewController.h"
#import "PKRequestManager.h"
#import "MQVideoEnterModel.h"
#import <MJRefresh.h>
#import "FMDatabase.h"
#import <MediaPlayer/MediaPlayer.h>
#import "Reachability.h"
#import "MQVideoEnterViewCell.h"
#import "UMSocial.h"
#import "MQVideoMainViewController.h"
#import "PKPlayerManger.h"
@interface MQVideoEntertainmentViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate,UIScrollViewDelegate>
@property (nonatomic, strong)NSMutableArray * dataArr;
@property (nonatomic, strong)UITableView * videoTableView;
@property (nonatomic, strong)NSMutableString * urlStr;
@property (nonatomic, strong)MPMoviePlayerController * player;
@property (nonatomic, assign)NSData * data;
@property (nonatomic, strong)NSString * np;
@property (nonatomic, strong)MQVideoEnterModel * model;
@property (nonatomic, strong)FMDatabase * db;
@property (nonatomic, strong)UILabel * remindLabel;
@property (nonatomic, strong)UIImageView * remindView;
@property (nonatomic, assign)BOOL isLoadNew;
@property (nonatomic, assign)UIScrollView * myScrollView;
@property (nonatomic, strong)NSMutableArray * dataBaseArr;
@property (nonatomic, strong)FMDatabase * database;
@property (nonatomic, assign)NSInteger num;
@end

@implementation MQVideoEntertainmentViewController

-(NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        self.dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}

-(NSMutableArray *)dataBaseArr
{

    if (_dataBaseArr == nil) {
        self.dataBaseArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataBaseArr;
    
}


-(void)requestData
{
    
    NSString * str1 = @"http:s.budejie.com/topic/list/jingxuan/41/budejie-android-6.1.5/";
    NSString * str2 =self.urlStr;
    NSString * str3 =@"-20.json?market=xiaomi&udid=99000658286126&appname=baisibudejie&os=4.4.4&client=android&visiting=&mac=58%3A44%3A98%3Add%3Abc%3A29&ver=6.1.5";
    
    if (self.urlStr.length==0) {
        str2 = @"0";
    }
    NSLog(@"%@",str2);
    NSString * url = [[str1 stringByAppendingString:str2]stringByAppendingString:str3];
    
    
    [PKRequestManager requestWithType:GET urlString:url parDic:nil finish:^(NSData *data) {
        [self creatDataBase];
        NSString *sql1 = [NSString stringWithFormat:@"delete from usrTable where dataName = ?"];
        [ _db executeUpdate:sql1,@"video" ];
               NSString *sql = [NSString stringWithFormat:@"insert into usrTable (dataName, jsonData) values (?, ?)"];
        [_db executeUpdate:sql, @"video", data];
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
        NSDictionary * dataDic = [dic objectForKey:@"info"];
        NSInteger count = [[dataDic objectForKey:@"count"]integerValue];
        NSString * np = [dataDic objectForKey:@"np"];
        NSArray * list = [dic objectForKey:@"list"];
        if(_isLoadNew==YES) {
            [self.dataArr removeAllObjects];
            
        }
        for (NSDictionary * dict in list) {
            MQVideoEnterModel * model = [[MQVideoEnterModel alloc]init];
            [model setValue:dict forKey:@"list"];
            [model setValue:[NSString stringWithFormat:@"%ld",(long)count] forKey:@"count"];
            [self.dataArr addObject:model];
            
        }
        [_videoTableView reloadData];
        
        _videoTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if ([self isConnectionAvailable]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    _isLoadNew = NO;
                    self.urlStr = [NSMutableString stringWithFormat:@"%@",np];
                    [self requestData];
                    
                    
                });

            }
            else
            {
            
                [self remindOfConnection];
                [self.videoTableView.footer endRefreshing];
                
            }
            
        }];
        
        [_videoTableView.header endRefreshing];
        [_videoTableView.footer endRefreshing];
       
        
        
        
        
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
}
//创建数据库
-(void)creatDataBase
{
    NSString *dbpath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"video.db"];
    _db = [FMDatabase databaseWithPath:dbpath];
    NSLog(@"%@",dbpath);
    
    if([_db open])
    {
        NSString *sql = [NSString stringWithFormat:@"create table  usrTable (dataName text primary key, jsonData blob)"];
        BOOL rs = [_db executeUpdate:sql];
        if(!rs)
        {
            NSLog(@"error create table!");
        }else
        {
            NSLog(@"successed create table!");
            
        }
    }
    
    
}

//从数据库中取出数据
-(void)queryFormDataBase
{
    NSString *sql = @"select jsonData from usrTable where dataName = ?";
    FMResultSet * rs = [_db executeQuery:sql, @"video"];
    while ([rs next])
    {
        
        NSData *jsonData = [rs dataForColumnIndex:0];
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
        NSDictionary * dataDic = [dic objectForKey:@"info"];
        NSInteger count = [[dataDic objectForKey:@"count"]integerValue];
        NSString * np = [dataDic objectForKey:@"np"];
        NSArray * list = [dic objectForKey:@"list"];
        for (NSDictionary * dict in list) {
            MQVideoEnterModel *  model = [[MQVideoEnterModel alloc]init];
            [model setValue:dict forKey:@"list"];
            [model setValue:[NSString stringWithFormat:@"%ld",(long)count] forKey:@"count"];
            [self.dataArr addObject:model];
            
        }
        self.urlStr = [NSMutableString stringWithFormat:@"%@", np];
       
    }
    [rs close];
    
}


-(NSArray *)creatArrDataBase
{

    NSString *dbpath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"model.db"];
    _database = [FMDatabase databaseWithPath:dbpath];
    if ([_database open]) {
       
           [_database executeUpdate:@"create table modelTable (title text)"];
        
    }
    NSString *sql = @"select * from modelTable ";
    FMResultSet * rs= [_database executeQuery:sql];
    while ([rs next]) {
        NSString * title = [rs  stringForColumn:@"title"];
        [self.dataBaseArr addObject:title];
    }
    [_database close];
   
    return self.dataBaseArr;
    
}


-(void)insertDataToDataBase:(NSString * )str
{
    NSString *dbpath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"model.db"];
    _database = [FMDatabase databaseWithPath:dbpath];
    if ([_database open])
    {
        [_database executeUpdate:@"create table modelTable (title text)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    
    [_database executeUpdate:@"insert into modelTable (title) values (?)",str];
    
    [_database close];
   

}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.num = 0;
    _urlStr = [NSMutableString string];
    _videoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height-110) style:(UITableViewStylePlain)];
    [self.view addSubview:_videoTableView];
    _videoTableView.dataSource = self;
    _videoTableView.delegate = self;
    [_videoTableView registerClass:[MQVideoEnterViewCell class] forCellReuseIdentifier:@"videocell"];
    
    
    //  创建数据库，从数据库中取出数据
    [self creatDataBase];
    [self queryFormDataBase];
    
    
    [self requestData];
    
    //    判断当前网络是否可用，可用请求数据，不可用从数据库取出数据
    
    _videoTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if ([self isConnectionAvailable]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                                _isLoadNew = YES;
                                self.urlStr = [NSMutableString stringWithFormat:@"%@",@"0"];
                                [self requestData];
                                
                            });
        }
        else
        {
            [self remindOfConnection];
            [self.videoTableView.header endRefreshing];
        }
    }];

    
    self.myScrollView.delegate = self;
}



-(void)remindOfConnection
{
    //                     没网的时候提醒用户
    _remindView = [[UIImageView alloc]initWithFrame:CGRectMake(30, screen_height/2, screen_width-60, 30)];
    _remindView.image = [UIImage imageNamed:@"bg_share_large"];
    [self.view addSubview:_remindView];
    _remindLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screen_width-60, 30)];
    _remindLabel.text = TITLE_MESSAGE;
    
    _remindLabel.textAlignment = NSTextAlignmentCenter;
    _remindLabel.textColor = [UIColor blackColor];
    [_remindView addSubview:_remindLabel];
    _remindView.backgroundColor = [UIColor darkGrayColor];
    _remindView.layer.cornerRadius =5;
    _remindView.layer.masksToBounds = YES;
    
    
    //                     延迟两秒移除提醒
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (int i = 1; i<self.view.subviews.count; i++) {
            [self.view.subviews[i] removeFromSuperview];
        }
        
    });
    
   
    
    
    
}



//判断当前网络状态
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability * hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([hostReach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //            NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //            NSLog(@"3G");
            break;
    }
    return isExistenceNetwork;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return self.dataArr.count;
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MQVideoEnterModel * video =self.dataArr[indexPath.row];
    MQVideoEnterViewCell * cell = [_videoTableView dequeueReusableCellWithIdentifier:@"videocell" forIndexPath:indexPath];
    cell.gifView.image = [UIImage imageNamed:@""];
    cell.gifView.userInteractionEnabled = YES;
    cell.backGroundView.userInteractionEnabled = YES;
    UIButton * playButton = cell.gifView.subviews[2];
    playButton.tag = 100+indexPath.row;
   
         [playButton addTarget:self action:@selector(playVideo:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [cell configCellWithModel:video];
    cell.upCountLabel.text = cell.upCountLabel.text;
    if (cell.gifView.subviews.count == 4) {
        [_player.view removeFromSuperview];
        [_player stop];
    }
    cell.upButton.tag = 1000+indexPath.row;
    cell.downButton.tag = 2000+indexPath.row;
    
    
    
    NSArray * array = [self creatArrDataBase];
    if ([array containsObject:video.list.text]) {
        video.isUpClick=YES;
    }
    if ([array containsObject:video.list.share_url]) {
        video.isDownClick = YES;
    }
    
        if (video.isUpClick==NO)
        {
            
           
                           [cell.upButton addTarget:self action:@selector(upZan:) forControlEvents:(UIControlEventTouchUpInside)];
                [cell.upButton setBackgroundImage:[UIImage imageNamed:@"unzan"] forState:(UIControlStateNormal)];
                cell.upCountLabel.textColor = [UIColor blackColor];
            
            
        }
        else
        {
            
            [cell.upButton setBackgroundImage:[UIImage imageNamed:@"zan"] forState:(UIControlStateNormal)];
            cell.upCountLabel.textColor = [UIColor redColor];
            
        }
        if (video.isDownClick==NO)
        {
            
            
          
            [cell.downButton addTarget:self action:@selector(down:) forControlEvents:(UIControlEventTouchUpInside)];
            
            [cell.downButton setBackgroundImage:[UIImage imageNamed:@"uncai"] forState:(UIControlStateNormal)];
            cell.downCountLabel.textColor = [UIColor blackColor];
            
            
        }
        else
        {
            
                         [cell.downButton setBackgroundImage:[UIImage imageNamed:@"cai"] forState:(UIControlStateNormal)];
            cell.downCountLabel.textColor = [UIColor redColor];
              
            
        }

       cell.shareButton.tag = 100+indexPath.row;
    [cell.shareButton addTarget:self action:@selector(share:) forControlEvents:(UIControlEventTouchUpInside)];
    return cell;
    
    
    
    
}

//点赞
-(void)upZan:(UIButton *)button
{

    
    
    MQVideoEnterModel * model = self.dataArr[button.tag-1000];
    if (model.isUpClick ==YES) {
        return;
    }
//    插入数据库
    [self insertDataToDataBase:model.list.text];
    
    MQVideoEnterViewCell * cell =(MQVideoEnterViewCell *) button.superview.superview.superview;
           [button setBackgroundImage:[UIImage imageNamed:@"zan"] forState:(UIControlStateNormal)];
         cell.upCountLabel.text =[NSString stringWithFormat:@"%ld", [cell.upCountLabel.text integerValue]+1];
        UILabel * addLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, -5, 20, 10)];
        addLabel.text = @"+1";
         [cell.upCountLabel addSubview:addLabel];
        cell.upCountLabel.textColor = [UIColor redColor];
        addLabel.textColor = [UIColor redColor];
        [UIView animateWithDuration:1.0 animations:^{
            addLabel.frame = CGRectMake(5, -5, 20, 10);
        
        } completion:^(BOOL finished) {
            addLabel.frame = CGRectZero;
        }];
    
    model.isUpClick= YES;
}
//踩
-(void)down:(UIButton*)button
{
    MQVideoEnterModel * model = self.dataArr[button.tag-2000];
    if (model.isDownClick==YES) {
        return;
    }
    [self insertDataToDataBase:model.list.share_url];
    MQVideoEnterViewCell * cell =(MQVideoEnterViewCell *) button.superview.superview.superview;
    [button setBackgroundImage:[UIImage imageNamed:@"cai"] forState:(UIControlStateNormal)];
    cell.downCountLabel.text =[NSString stringWithFormat:@"%ld", [cell.downCountLabel.text integerValue]+1];
    UILabel * addLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, -5, 20, 10)];
    addLabel.text = @"+1";
    [cell.downCountLabel addSubview:addLabel];
    cell.downCountLabel.textColor = [UIColor redColor];
    addLabel.textColor = [UIColor redColor];
    [UIView animateWithDuration:1.0 animations:^{
        addLabel.frame = CGRectMake(5, -5, 20, 10);
        
    } completion:^(BOOL finished) {
        addLabel.frame = CGRectZero;
    }];
    
    model.isDownClick = YES;
}
//分享
-(void)share:(UIButton*)button
{

   
    MQVideoEnterViewCell * cell =(MQVideoEnterViewCell *) button.superview.superview.superview;
    MQVideoEnterModel * model = self.dataArr[button.tag-100];
    
    [UMSocialSnsService presentSnsIconSheetView:self.mainVC
                                appKey:@"561b79fde0f55ac7c00016bf"
                                      shareText:model.list.share_url
                                     shareImage:cell.backGroundView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];

   
}

//点击button播放视频
-(void)playVideo:(UIButton *)button
{
    [[PKPlayerManger shareManger] stop];
    if (button.tag !=self.num && self.num !=0) {
        [_player.view removeFromSuperview];
        [_player stop];
    }
    
    self.num = button.tag;
   MQVideoEnterModel * model= self.dataArr[button.tag -100];
    
    _player = [[MPMoviePlayerController alloc]init];
    [_player setContentURL: [NSURL URLWithString:model.list.video.video[0]]];
    _player.view.frame =CGRectMake(0, 0, button.superview.frame.size.width, button.superview.frame.size.height) ;
   
    [button.superview addSubview:_player.view];
    [_player play];
//    播放结束的时候添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerStop) name:@"xxx" object:nil];
    
}

-(void)playerStop
{

    [_player stop];
    [_player.view removeFromSuperview];
    
}


//、结束后移除播放器的View
-(void)playerFinish:(NSNotification*)notification
{
    [_player.view removeFromSuperview];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return [MQVideoEnterViewCell heightForRowWithmodel:self.dataArr[indexPath.row]];
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [_player.view removeFromSuperview];
    [_player stop];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
